<?php
class M_ujian extends CI_Model {


	// (nomer ujian siswa, Urut Ujian, token ujian)
	function pronilai($XNomerUjian,$Urut,$token){

		$this->db->select("*,u.Urut XIdUjian");
		$this->db->from("cbt_ujian u");
		$this->db->join("cbt_tes t","u.XKodeUjian = t.XKodeUjian");
		$this->db->join("cbt_paketsoal p","u.XKodeSoal = p.XKodeSoal");
		$this->db->join("cbt_mapel m","m.XKodeMapel = p.XKodeMapel");
		// $this->db->where("XStatusUjian",1);

		$this->db->where("u.Urut",$Urut);
		$this->db->where("u.XTokenUjian",$token);
		$uj=$this->db->get()->row();
		// print_r($uj);

    	$this->db->where("XIdUjian",$Urut);
    	$this->db->where("XTokenUjian",$token);
    	$this->db->where("XNomerUjian",$XNomerUjian);
    	$query['jawaban']=$this->db->get('cbt_jawaban');


    	$data=[
    		"benar"=>0,
    		"salah"=>0
    	];


    	foreach ($query['jawaban']->result() as $key => $value) {
    		if ($value->XNilaiJawab == $value->XKunciJawaban) {
    			$data['benar']++;
    		} else {
    			$data['salah']++;
    		}
    	}

    	$jumpil=ceil((int) ($data['benar'] + $data['salah']));

    	$data['nilai']=round((($data['benar']/$jumpil)*$uj->XPersenPil),2);
    	$submit['nilai']=[
    		'XIdUjian' => $Urut,
    		'XNomerUjian' => $XNomerUjian, 
			'XTokenUjian' => $token, 
			'XTgl' => date("Y-m-d"), 
			'XJumSoal' => $jumpil, 
			'XBenar' => $data['benar'], 
			'XSalah' => $data['salah'], 
			'XNilai' => $data['nilai'], 
			'XPersenPil' => $uj->XPersenPil, 
			// 'XPersenEsai' => $uj->XPersenEsai, 
			// 'XEsai' => $->XEsai, 
			'XTotalNilai' => $data['nilai'], 
			'XPilGanda' => $uj->XPilGanda, 
			'XStatus' => 9, 
		];

		// $this->db->where("XIdUjian",$Urut);
		// $this->db->where("XTokenUjian",$token);
		// $this->db->where("XNomerUjian",$XNomerUjian);


		$this->db->where("XIdUjian",$Urut);
		$this->db->where("XTokenUjian",$token);
		$this->db->where("XNomerUjian",$XNomerUjian);

		if ($this->db->get("cbt_nilai")->num_rows() == 0) {
			$query=$this->db->insert("cbt_nilai",$submit['nilai']);
		} else {
			$this->db->where("XIdUjian",$Urut);
			$this->db->where("XTokenUjian",$token);
			$this->db->where("XNomerUjian",$XNomerUjian);
			$query=$this->db->update("cbt_nilai",$submit['nilai']);
		}


		if ($query) {
			// set ke selesai mengerjakan
			$this->db->where("XIdUjian",$Urut);
    		$this->db->where("XTokenUjian",$token);
    		$this->db->where("XNomerUjian",$XNomerUjian);
    		$this->db->update("cbt_siswa_ujian",['XStatusUjian' =>1,"LastUpdate" => time()]);
    		return true;
		} else {
			return false;
		}
	}
}
